package com.doudou.pay.helper.service.impl;

import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.doudou.pay.helper.commons.PayConstans;
import com.doudou.pay.helper.commons.PayRedisKey;
import com.doudou.pay.helper.entities.PayNotifyResult;
import com.doudou.pay.helper.entities.ResponsePay;
import com.doudou.pay.helper.service.MessageCacheService;

@Service("messageCacheService")
public class MessageCacheServiceImpl implements MessageCacheService {
	
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
	@Override
	public ResponsePay getResponsePay(String sessionKey) {
		String jsonText = stringRedisTemplate.opsForValue().get(PayRedisKey.getResponsePayKey(sessionKey));
		if(StringUtils.isNotEmpty(jsonText)) {
			return JSON.parseObject(jsonText, ResponsePay.class);
		}
		return null;
	}

	@Override
	public PayNotifyResult getPayNotifyResult(String sessionKey) {
		String jsonText = stringRedisTemplate.opsForValue().get(PayRedisKey.getPayNotifyKey(sessionKey));
		if(StringUtils.isNotEmpty(jsonText)) {
			return JSON.parseObject(jsonText, PayNotifyResult.class);
		}
		return null;
	}

	@Override
	public void setResponsePay(ResponsePay responsePay) {
		stringRedisTemplate.opsForValue().set(
				PayRedisKey.getResponsePayKey(responsePay.getSessionKey()),
				JSON.toJSONString(responsePay), 
				PayConstans.PAY_VALID_TIME, 
				TimeUnit.MINUTES);
	}

	@Override
	public void removeResponsePay(String sessionKey) {
		stringRedisTemplate.delete(PayRedisKey.getResponsePayKey(sessionKey));
	}

	@Override
	public void setPayNotifyResult(PayNotifyResult payNotifyResult) {
		stringRedisTemplate.opsForValue().set(
				PayRedisKey.getPayNotifyKey(payNotifyResult.getSessionKey()),
				JSON.toJSONString(payNotifyResult), 
				PayConstans.PAY_VALID_TIME, 
				TimeUnit.MINUTES);
	}

	@Override
	public void removePayNotifyResult(String sessionKey) {
		stringRedisTemplate.delete(PayRedisKey.getPayNotifyKey(sessionKey));
	}

}
